import {ResponseHandler} from '#src/common/utils/http/responseHandler.js';
import {HTTP_STATUS} from '#src/constants/http.constants.js';
import {logger} from '#src/common/utils/logger.js';
import {AuthMessage, UserMessage} from '#src/constants/message.constants.js';
import jwtService from '#src/common/services/auth/JwtService.js';
// 身份验证中间件
export const authenticate = (req, res, next) => {
    // 1. 优先从 Authorization Header 获取
    const authHeader = req.headers.authorization;
    let token = null;

    // 2. 支持从 URL 查询参数获取 (添加此段逻辑)
    if (authHeader && authHeader.startsWith('Bearer ')) {
        token = authHeader.split(' ')[1];
    } else if (req.query.token) {
        // 从查询参数获取 token
        token = req.query.token;
        logger.info('从URL查询参数获取token', {path: req.path});
    }

    // 3. 验证 token 是否存在
    if (!token) {
        logger.warn('身份验证失败：未提供token（支持Authorization: Bearer 或 ?token=xxx）', {path: req.path});
        return res.status(HTTP_STATUS.UNAUTHORIZED)
            .json(ResponseHandler.error(AuthMessage.TOKEN_MISSING, HTTP_STATUS.UNAUTHORIZED));
    }

    try {
        req.user = jwtService.verifyToken(token);
        ;
        next();
    } catch (error) {
        logger.error('Token验证失败', {
            path: req.path,
            error: error.message
        });

        let errorMessage = '身份验证失败';
        let statusCode = HTTP_STATUS.UNAUTHORIZED;

        if (error.name === 'TokenExpiredError') {
            errorMessage = AuthMessage.TOKEN_EXPIRED;
        } else if (error.name === 'JsonWebTokenError') {
            errorMessage = AuthMessage.TOKEN_INVALID;
        }

        return res.status(statusCode)
            .json(ResponseHandler.error(errorMessage, statusCode));
    }
};

// 角色验证中间件
export const requireRole = (allowedRoles) => {
    return (req, res, next) => {
        if (!req.user || !req.user.role) {
            return res.status(HTTP_STATUS.FORBIDDEN)
                .json(ResponseHandler.error(UserMessage.FORBIDDEN, HTTP_STATUS.FORBIDDEN));
        }
        if (allowedRoles.includes(req.user.role)) {
            next();
        } else {
            logger.warn('角色权限不足', {
                path: req.path,
                userRole: req.user.role,
                requiredRoles: allowedRoles
            });
            return res.status(HTTP_STATUS.FORBIDDEN)
                .json(ResponseHandler.error(UserMessage.PERMISSION_DENIED, HTTP_STATUS.FORBIDDEN));
        }
    };
};
// 检查请求中是否包含用户信息的中间件
export const checkUserExists = (req, res, next) => {
    if (!req.user) {
        logger.warn('请求中缺少用户信息', {path: req.path});
        return res.status(HTTP_STATUS.UNAUTHORIZED)
            .json(ResponseHandler.error(UserMessage.MISSING_INFO, HTTP_STATUS.UNAUTHORIZED));
    }
    next();
};
